package com.hjw.exception;

import java.sql.SQLIntegrityConstraintViolationException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SaTokenException.class)
    public SaResult handlerSaTokenException(SaTokenException e) {
        log.error("SaTokenException: {}", e.getMessage());
        // 根据不同异常细分状态码返回不同的提示
        if(e.getCode() == 30001) {
            return SaResult.error("redirect 重定向 url 是一个无效地址");
        }
        if(e.getCode() == 30002) {
            return SaResult.error("redirect 重定向 url 不在 allowUrl 允许的范围内");
        }
        if(e.getCode() == 30004) {
            return SaResult.error("提供的 ticket 是无效的");
        }
        if(e.getCode() == 11041) {
            return SaResult.error("缺少指定的角色");
        }
        if(e.getCode() == 11051) {
            return SaResult.error("缺少指定的权限");
        }
        if(e.getCode() == 11012) {
            return SaResult.get(401,"Token无效",null);
        }
        if(e.getCode() == 11011){
            return SaResult.error("请求中无Token");
        }
        if(e.getCode() == 11013){
            return SaResult.error("Token已过期");
        }
        // 更多 code 码判断 ...

        // 默认的提示
        return SaResult.error("服务器繁忙，请稍后重试...");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public SaResult handlerIllegalArgumentException(IllegalArgumentException e) {
        log.error("IllegalArgumentException: {}", e.getMessage());
        return SaResult.error("参数错误：" + e.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public SaResult handlerSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        log.error("SQLIntegrityConstraintViolationException: {}", e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            return SaResult.get(-200,"数据重复或已存在",null);
        }
        return SaResult.get(-200,"数据库错误",null);
    }
}
